const app = getApp();
const db = wx.cloud.database();
Page({
  data: {
    id: '',
    input: '',
    todos: [],
    leftCount: 0,
    allCompleted: false,
    logs: [],
    toastHidden: true,
  },
  onShow: function () {
    wx.setNavigationBarTitle({
      title: '待办清单'
    })

  },

  get_cloud() {
    var _this = this;
    return new Promise((resolve, reject) => {
      db.collection('user').where({
        _id: _this.data.id,
      }).get({
        success: res => {
          let user = res.data[0];
          _this.setData({
            todos:user.todo_list,
            logs:user.todo_logs
          })
          resolve(res)
        },
        fail: res => {
          reject('失败啦')
        }
      })
    })
  },

  useData() {
    var _this = this;
    this.get_cloud().then(res => {
      var todos = _this.data.todos
      if (todos) {
        var leftCount = todos.filter(function (item) {
          return !item.completed
        }).length
        _this.setData({
          todos: todos,
          leftCount: leftCount
        })
      }
      var logs = _this.data.logs
      if (logs) {
        _this.setData({
          logs: logs
        })
      }
    }).catch(res =>{
      console.log(res)
    }) 
  },

  save: function () {
    wx.setStorageSync('todo_list', this.data.todos)
    wx.setStorageSync('todo_logs', this.data.logs)
  },

  update_cloud() {
    var _this = this;
    db.collection('user').where({
      _id: _this.data.id,
    }).update({
      data: {
        todo_list: _this.data.todos,
        todo_logs: _this.data.logs,
      },
      success: function (res) {
        console.log(res[0].data.todo_list)
      }
    })
  },

  load: function () {
    this.setData({
      id: app.globalData.id,
    })
    this.useData()
  },

  onLoad: function () {
    this.load()
  },

  inputChangeHandle: function (e) {
    this.setData({
      input: e.detail.value
    })
  },

  addTodoHandle: function (e) {
    if (!this.data.input || !this.data.input.trim()) return
    var todos = this.data.todos
    todos.push({
      name: this.data.input,
      completed: false
    })
    var logs = this.data.logs
    logs.push({
      timestamp: new Date(),
      action: 'Add',
      name: this.data.input
    })
    this.setData({
      input: '',
      todos: todos,
      leftCount: this.data.leftCount + 1,
      logs: logs
    })
    this.update_cloud()
  },

  toggleTodoHandle: function (e) {
    var index = e.currentTarget.dataset.index
    var todos = this.data.todos
    todos[index].completed = !todos[index].completed
    var logs = this.data.logs
    logs.push({
      timestamp: new Date(),
      action: todos[index].completed ? 'Finish' : 'Restart',
      name: todos[index].name
    })
    this.setData({
      todos: todos,
      leftCount: this.data.leftCount + (todos[index].completed ? -1 : 1),
      logs: logs
    })
    this.update_cloud()

  },

  removeTodoHandle: function (e) {
    var index = e.currentTarget.dataset.index
    var todos = this.data.todos
    var remove = todos.splice(index, 1)[0]
    var logs = this.data.logs
    logs.push({
      timestamp: new Date(),
      action: 'Remove',
      name: remove.name
    })
    this.setData({
      todos: todos,
      leftCount: this.data.leftCount - (remove.completed ? 0 : 1),
      logs: logs
    })
    this.update_cloud()
  },

  toggleAllHandle: function (e) {
    this.data.allCompleted = !this.data.allCompleted
    var todos = this.data.todos
    for (var i = todos.length - 1; i >= 0; i--) {
      todos[i].completed = this.data.allCompleted
    }
    var logs = this.data.logs
    logs.push({
      timestamp: new Date(),
      action: this.data.allCompleted ? 'Finish' : 'Restart',
      name: 'All todos'
    })
    this.setData({
      todos: todos,
      leftCount: this.data.allCompleted ? 0 : todos.length,
      logs: logs
    })
    this.update_cloud()
    wx.vibrateShort()
  },

  clearCompletedHandle: function (e) {
    var todos = this.data.todos
    var remains = []
    for (var i = 0; i < todos.length; i++) {
      todos[i].completed || remains.push(todos[i])
    }
    var logs = this.data.logs
    logs.push({
      timestamp: new Date(),
      action: 'Clear',
      name: 'Completed todo'
    })
    this.setData({
      todos: remains,
      logs: logs
    })
    this.update_cloud()
    this.setData({
      toastHidden: false
    })
    wx.vibrateShort()
  },
  hideToast: function () {
    this.setData({
      toastHidden: true
    })
  },
  onShareAppMessage: function (res) {

    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
      return {
        title: '管理时间，保持专注！让自律成为习惯！',
        path: '/pages/index/index',
        imageUrl: '/image/share.jpg' //不设置则默认为当前页面的截图
      }
    }
  },
  onShareTimeline: function (res) {
    return {
      title: '管理时间，保持专注，让自律成为习惯！',
      query: {
        // key: 'value' //要携带的参数 
      },
      imageUrl: '/image/about.png'
    }
  }

})